package com.poisonh.unifiedauth.ui;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Matrix;
import android.graphics.Rect;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.google.zxing.WriterException;
import com.lzy.okhttputils.model.HttpParams;
import com.poisonh.unifiedauth.R;
import com.poisonh.unifiedauth.dialog.MerchantsDialogFragment;
import com.poisonh.unifiedauth.dialog.PopWindow;
import com.poisonh.unifiedauth.model.BusinessCard;
import com.poisonh.unifiedauth.model.IdCard;
import com.poisonh.unifiedauth.utils.ConstantUitls;
import com.poisonh.unifiedauth.utils.GlideCircleTransform;
import com.poisonh.unifiedauth.utils.MyHttpsUtils;
import com.poisonh.unifiedauth.utils.TOTPUtils;
import com.poisonh.unifiedauth.zxing.encoding.EncodingHandler;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.UnsupportedEncodingException;

import io.realm.Realm;

import static com.poisonh.unifiedauth.ui.MainActivity.MESSAGE_ACTION_AUTHORIZATION;

/**
 * 我的信息
 * Created by PoisonH on 2016/6/24.
 */
public class MyInfoActivity extends BaseActivity implements View.OnClickListener, PopWindow.ClickPositionListener
{
    private ImageView mIvUserInfoCode;
    private ImageView mIvInfoHead;
    private TextView mTvInfoScore;
    private TextView mTvInfoName;
    private ImageView mIvInfoSex;
    private Runnable mRunnable;

    private BusinessCard mBusinessCard;
    private IdCard mIdCard;
    public static final String KEY_MESSAGE = "message";
    public static final String KEY_EXTRAS = "extras";

    private Handler mHandler = new Handler();
    private String msg;
    private MessageReceiver mMessageReceiver;

    @Override
    protected void loadContentView(Bundle savedInstanceState)
    {
        setContentView(R.layout.activity_mycodeinfo);
        initTitleView();
        setTitleTxt("我的身份");
        loadData();
        initView();
        registerMessageReceiver();
       // findUserInfoById();
        this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_SECURE);//禁止截屏
    }


    @Override
    protected void initView()
    {
        mIvUserInfoCode = (ImageView) findViewById(R.id.iv_info_code);

        mIvInfoHead = (ImageView) findViewById(R.id.iv_info_head);
        mIvInfoSex = (ImageView) findViewById(R.id.iv_info_sex);
        mTvInfoScore = (TextView) findViewById(R.id.tv_info_score);
        mTvInfoName = (TextView) findViewById(R.id.tv_info_name);

        initUserInfo();

        mLeftBtn.setOnClickListener(this);
        mRunnable = new Runnable()
        {
            @Override
            public void run()
            {
                totp();
                mHandler.postDelayed(mRunnable, 1000);
            }
        };
        mRightBtn.setOnClickListener(this);
    }

    /**
     * 初始化用户信息
     */
    private void initUserInfo()
    {

        Realm realm = Realm.getDefaultInstance();

        if (mBusinessCard != null)
        {
            mTvInfoName.setText(mBusinessCard.getName());
            //Glide.with(this.getApplicationContext()).load(ConstantUitls.REQUEDT_IMG_URL + mBusinessCard.getHeadImg()).into(mIvInfoHead);
            Glide.with(this).load(ConstantUitls.REQUEDT_IMG_URL+mBusinessCard.getHeadImg()).transform(new GlideCircleTransform(this)).into(mIvInfoHead);
        }
        else if(mIdCard!=null){

            if(mIdCard.getCompareImg()!=null){
                mTvInfoName.setText(mIdCard.getName());
               // Glide.with(this.getApplicationContext()).load(ConstantUitls.REQUEDT_IMG_URL + mIdCard.getCompareImg()).into(mIvInfoHead);
                Glide.with(this).load(ConstantUitls.REQUEDT_IMG_URL+ mIdCard.getCompareImg()).transform(new GlideCircleTransform(this)).into(mIvInfoHead);
            }
        }else
        {
            mTvInfoName.setText(mStrUserPhone);
            //Glide.with(this.getApplicationContext()).load(ConstantUitls.REQUEDT_IMG_URL + ConstantUitls.DEFAULTHEADIMG).into(mIvInfoHead);
            Glide.with(this).load(ConstantUitls.REQUEDT_IMG_URL+ ConstantUitls.DEFAULTHEADIMG).transform(new GlideCircleTransform(this)).into(mIvInfoHead);
        }

    }

    @Override
    public void onClick(View v)
    {
        switch (v.getId())
        {
            case R.id.ib_left_btn:
                finish();
                break;

            case R.id.ib_right_btn:
                showPopupWindow();
                break;
        }
    }

    /**
     * 时间同步
     */
    private void totp()
    {
        String totp = TOTPUtils.generate(mStrUserToken);

        String content = "Certification," + mStrUserId + "," + totp.trim();

        Bitmap bitmap = create2Code(content);
        Bitmap headBitmap = getHeadBitmap(60);
        if (bitmap != null && headBitmap != null)
        {
            createQRCodeBitmapWithPortrait(bitmap, headBitmap);
        }
    }

    /**
     * 生成二维码
     *
     * @param key
     */
    private Bitmap create2Code(String key)
    {
        Bitmap qrCode = null;
        try
        {
            qrCode = EncodingHandler.create2Code(key, 600);
            mIvUserInfoCode.setImageBitmap(qrCode);
        } catch (WriterException e)
        {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e)
        {
            e.printStackTrace();
        }
        return qrCode;
    }

    /**
     * 初始化头像图片
     */
    private Bitmap getHeadBitmap(int size)
    {
        try
        {
            // 这里采用从asset中加载图片abc.jpg
            Bitmap portrait = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
            // 对原有图片压缩显示大小
            Matrix mMatrix = new Matrix();
            float width = portrait.getWidth();
            float height = portrait.getHeight();
            mMatrix.setScale(size / width, size / height);
            return Bitmap.createBitmap(portrait, 0, 0, (int) width, (int) height, mMatrix, true);
        } catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 在二维码上绘制头像
     */
    private void createQRCodeBitmapWithPortrait(Bitmap qr, Bitmap portrait)
    {
        // 头像图片的大小
        int portrait_W = portrait.getWidth();
        int portrait_H = portrait.getHeight();

        // 设置头像要显示的位置，即居中显示
        int left = (qr.getWidth() - portrait_W) / 2;
        int top = (qr.getHeight() - portrait_H) / 2;
        int right = left + portrait_W;
        int bottom = top + portrait_H;
        Rect rect1 = new Rect(left, top, right, bottom);

        // 取得qr二维码图片上的画笔，即要在二维码图片上绘制我们的头像
        Canvas canvas = new Canvas(qr);

        // 设置我们要绘制的范围大小，也就是头像的大小范围
        Rect rect2 = new Rect(0, 0, portrait_W, portrait_H);
        // 开始绘制
        canvas.drawBitmap(portrait, rect2, rect1, null);
    }

    @Override
    public void onResume()
    {
        super.onResume();

        mHandler.post(mRunnable);
    }

    @Override
    public void onPause()
    {
        super.onPause();

        mHandler.removeCallbacks(mRunnable);
    }

    private void showPopupWindow()
    {
        PopWindow popWindow = new PopWindow(this);
        popWindow.showPopupWindow(mRightBtn);
    }

    @Override
    public void onClickPosition(int pos)
    {
        if (pos == 0)
        {
            startActivity(new Intent(MyInfoActivity.this, VerRecordActivity.class));
        } else if (pos == 1)
        {
            startActivity(new Intent(MyInfoActivity.this, HelpActvity.class));
        }
    }

    /**
     * 查询用户信息
     */
    private void findUserInfoById()
    {
        HttpParams params = new HttpParams();
        params.put("id", mStrUserId);
        params.put("token", mStrUserToken);
        MyHttpsUtils.post(ConstantUitls.REQUEDT_URL + ConstantUitls.FINDUSERINFOBYID, params, new MyHttpsUtils.ResultCallback()
        {
            @Override
            public void onSuccess(String response)
            {
                try
                {
                    JSONObject json = new JSONObject(response);
                    JSONObject data = json.getJSONObject("results");
                    String url = data.getString("headImgUrl");
                    Glide.with(MyInfoActivity.this).load(ConstantUitls.REQUEDT_IMG_URL + url).into(mIvInfoHead);
                    String sex = data.getString("sex");
                    if (sex.equals("0"))
                    {
                        mIvInfoSex.setBackgroundResource(R.drawable.icon_woman);

                    } else if (sex.equals("1"))
                    {
                        mIvInfoSex.setBackgroundResource(R.drawable.icon_man);
                    } else
                    {
                        mIvInfoSex.setVisibility(View.GONE);
                    }
                    mTvInfoName.setText(data.getString("nick"));
                    //mTvInfoScore.setText("用户评分：" + data.getString("score") + "分");
                } catch (JSONException e)
                {
                    e.printStackTrace();
                }
            }

            @Override
            public void onFailure(String failReason)
            {
                Glide.with(MyInfoActivity.this).load(mStrUserHeadUrl).into(mIvInfoHead);
                mIvInfoSex.setVisibility(View.GONE);
                if (mStrUserName != null)
                {
                    mTvInfoName.setText(mStrUserName);

                } else
                {
                    mTvInfoName.setText(mStrUserPhone);
                }
                //mTvInfoScore.setText("用户评分：" + mStrUserScore + "分");
            }
        });
    }

    private void loadData(){
        Realm realm = Realm.getDefaultInstance();
        mBusinessCard = realm.where(BusinessCard.class).equalTo("uid",mStrUserId).findFirst();
        mIdCard = realm.where(IdCard.class).equalTo("uid", mStrUserId).findFirst();
        realm.close();
    }

    public void registerMessageReceiver() {
        mMessageReceiver = new MessageReceiver();
        IntentFilter filter = new IntentFilter();
        filter.setPriority(IntentFilter.SYSTEM_HIGH_PRIORITY);
        filter.addAction(MESSAGE_ACTION_AUTHORIZATION);
        registerReceiver(mMessageReceiver, filter);
    }

    public class MessageReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String messge = intent.getStringExtra(KEY_MESSAGE);

            try {
                JSONObject object = new JSONObject(messge);
                msg=object.getString("msg");//入所扫描商户名称

            } catch (JSONException e) {
                e.printStackTrace();
            }
            if(MESSAGE_ACTION_AUTHORIZATION.equals(intent.getAction())){
                MerchantsDialogFragment merchantsDialogFragment=new MerchantsDialogFragment();
                Bundle mBundle = new Bundle();
                mBundle.putString("msg",msg);
                merchantsDialogFragment.setArguments(mBundle);
                merchantsDialogFragment.show(getFragmentManager(), "");
            }
        }
    }
}
